from flask import Blueprint, jsonify, request
from ..models.external_facility import ExternalOilDepot, ExternalAmmunitionDepot, Refinery
from ..models.airport import Airport
from ..models.runway import Runway
from ..models.parking_apron import ParkingApron
from ..models.oil_tank import OilTank
from ..models.ammunition_depot import AmmunitionDepot
from .. import db
from sqlalchemy import func

bp = Blueprint('external_facilities', __name__, url_prefix='/api/external')

# External Oil Depots
@bp.route('/oil-depots', methods=['GET'])
def get_external_oil_depots():
    oil_depots = ExternalOilDepot.query.all()
    return jsonify([depot.to_dict() for depot in oil_depots])

@bp.route('/oil-depots/<int:id>', methods=['GET'])
def get_external_oil_depot(id):
    oil_depot = ExternalOilDepot.query.get_or_404(id)
    return jsonify(oil_depot.to_dict())

@bp.route('/oil-depots', methods=['POST'])
def create_external_oil_depot():
    data = request.json
    oil_depot = ExternalOilDepot(
        name=data['name'],
        location=data['location'],
        capacity=data['capacity'],
        latitude=data['latitude'],
        longitude=data['longitude'],
        type=data['type']
    )
    db.session.add(oil_depot)
    db.session.commit()
    return jsonify(oil_depot.to_dict()), 201

@bp.route('/oil-depots/<int:id>', methods=['PUT'])
def update_external_oil_depot(id):
    oil_depot = ExternalOilDepot.query.get_or_404(id)
    data = request.json
    
    oil_depot.name = data.get('name', oil_depot.name)
    oil_depot.location = data.get('location', oil_depot.location)
    oil_depot.capacity = data.get('capacity', oil_depot.capacity)
    oil_depot.latitude = data.get('latitude', oil_depot.latitude)
    oil_depot.longitude = data.get('longitude', oil_depot.longitude)
    oil_depot.type = data.get('type', oil_depot.type)
    
    db.session.commit()
    return jsonify(oil_depot.to_dict())

@bp.route('/oil-depots/<int:id>', methods=['DELETE'])
def delete_external_oil_depot(id):
    oil_depot = ExternalOilDepot.query.get_or_404(id)
    db.session.delete(oil_depot)
    db.session.commit()
    return '', 204

# External Ammunition Depots
@bp.route('/ammunition-depots', methods=['GET'])
def get_external_ammunition_depots():
    ammo_depots = ExternalAmmunitionDepot.query.all()
    return jsonify([depot.to_dict() for depot in ammo_depots])

@bp.route('/ammunition-depots/<int:id>', methods=['GET'])
def get_external_ammunition_depot(id):
    ammo_depot = ExternalAmmunitionDepot.query.get_or_404(id)
    return jsonify(ammo_depot.to_dict())

@bp.route('/ammunition-depots', methods=['POST'])
def create_external_ammunition_depot():
    data = request.json
    ammo_depot = ExternalAmmunitionDepot(
        name=data['name'],
        location=data['location'],
        capacity=data['capacity'],
        latitude=data['latitude'],
        longitude=data['longitude'],
        type=data['type']
    )
    db.session.add(ammo_depot)
    db.session.commit()
    return jsonify(ammo_depot.to_dict()), 201

@bp.route('/ammunition-depots/<int:id>', methods=['PUT'])
def update_external_ammunition_depot(id):
    ammo_depot = ExternalAmmunitionDepot.query.get_or_404(id)
    data = request.json
    
    ammo_depot.name = data.get('name', ammo_depot.name)
    ammo_depot.location = data.get('location', ammo_depot.location)
    ammo_depot.capacity = data.get('capacity', ammo_depot.capacity)
    ammo_depot.latitude = data.get('latitude', ammo_depot.latitude)
    ammo_depot.longitude = data.get('longitude', ammo_depot.longitude)
    ammo_depot.type = data.get('type', ammo_depot.type)
    
    db.session.commit()
    return jsonify(ammo_depot.to_dict())

@bp.route('/ammunition-depots/<int:id>', methods=['DELETE'])
def delete_external_ammunition_depot(id):
    ammo_depot = ExternalAmmunitionDepot.query.get_or_404(id)
    db.session.delete(ammo_depot)
    db.session.commit()
    return '', 204

# Refineries
@bp.route('/refineries', methods=['GET'])
def get_refineries():
    refineries = Refinery.query.all()
    return jsonify([refinery.to_dict() for refinery in refineries])

@bp.route('/refineries/<int:id>', methods=['GET'])
def get_refinery(id):
    refinery = Refinery.query.get_or_404(id)
    return jsonify(refinery.to_dict())

@bp.route('/refineries', methods=['POST'])
def create_refinery():
    data = request.json
    refinery = Refinery(
        name=data['name'],
        location=data['location'],
        capacity=data['capacity'],
        latitude=data['latitude'],
        longitude=data['longitude']
    )
    db.session.add(refinery)
    db.session.commit()
    return jsonify(refinery.to_dict()), 201

@bp.route('/refineries/<int:id>', methods=['PUT'])
def update_refinery(id):
    refinery = Refinery.query.get_or_404(id)
    data = request.json
    
    refinery.name = data.get('name', refinery.name)
    refinery.location = data.get('location', refinery.location)
    refinery.capacity = data.get('capacity', refinery.capacity)
    refinery.latitude = data.get('latitude', refinery.latitude)
    refinery.longitude = data.get('longitude', refinery.longitude)
    
    db.session.commit()
    return jsonify(refinery.to_dict())

@bp.route('/refineries/<int:id>', methods=['DELETE'])
def delete_refinery(id):
    refinery = Refinery.query.get_or_404(id)
    db.session.delete(refinery)
    db.session.commit()
    return '', 204

@bp.route('/geo-data', methods=['GET'])
def get_geo_data():
    """获取地图数据，包括机场位置和地理边界"""
    airports = Airport.query.all()
    
    # 构建机场位置数据
    airport_locations = []
    for airport in airports:
        # 计算重要性指标（基于设施数量）
        runway_count = Runway.query.filter_by(airport_id=airport.id).count()
        apron_count = ParkingApron.query.filter_by(airport_id=airport.id).count() 
        oil_count = OilTank.query.filter_by(airport_id=airport.id).count()
        ammo_count = AmmunitionDepot.query.filter_by(airport_id=airport.id).count()
        
        # 计算重要性值（1-10之间）
        importance = min(10, 1 + (runway_count + apron_count + oil_count + ammo_count))
        
        # 获取地区对应的颜色
        color = '#c23531'  # 默认红色
        if airport.region == 'taichung':
            color = '#61a0a8'  # 台中区域 - 蓝绿色
        elif airport.region == 'tainan':
            color = '#d48265'  # 台南区域 - 橙色
        
        airport_locations.append({
            'name': airport.name,
            'region': airport.region,
            'latlng': [airport.latitude, airport.longitude],
            'value': importance,
            'color': color
        })
    
    # 构建台湾地理边界数据
    taiwan_geo_data = {
        'type': 'Feature',
        'properties': {'name': 'Taiwan'},
        'geometry': {
            'type': 'Polygon',
            'coordinates': [[
                [120.106, 23.167],  # 嘉义
                [120.646, 24.162],  # 台中
                [121.567, 25.037],  # 台北
                [121.868, 24.791],  # 宜兰
                [121.612, 23.976],  # 花莲
                [120.944, 23.507],  # 台东
                [120.585, 22.632],  # 高雄
                [120.203, 22.991],  # 台南
                [120.106, 23.167]   # 回到嘉义
            ]]
        }
    }
    
    # 构建高速公路数据
    highway_data = {
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'properties': {'name': '1号高速公路', 'type': 'highway'},
                'geometry': {
                    'type': 'LineString',
                    'coordinates': [
                        [121.567, 25.037],  # 台北
                        [121.20, 24.8],     # 桃园
                        [120.9, 24.5],      # 新竹
                        [120.646, 24.162],  # 台中
                        [120.4, 23.7],      # 嘉义
                        [120.203, 22.991],  # 台南
                        [120.3, 22.632]     # 高雄
                    ]
                }
            },
            {
                'type': 'Feature',
                'properties': {'name': '3号高速公路', 'type': 'highway'},
                'geometry': {
                    'type': 'LineString',
                    'coordinates': [
                        [121.45, 25.0],    # 台北东部
                        [121.4, 24.8],     # 基隆方向
                        [121.3, 24.6],     # 宜兰方向
                        [121.1, 24.2],     # 花莲北部
                        [121.0, 23.8],     # 花莲
                        [120.95, 23.5]     # 台东
                    ]
                }
            }
        ]
    }
    
    # 构建河流数据
    river_data = {
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'properties': {'name': '淡水河', 'type': 'river'},
                'geometry': {
                    'type': 'LineString',
                    'coordinates': [
                        [121.45, 25.18],  # 河口
                        [121.53, 25.07],  # 台北市内
                        [121.57, 24.95]   # 上游
                    ]
                }
            },
            {
                'type': 'Feature',
                'properties': {'name': '高屏溪', 'type': 'river'},
                'geometry': {
                    'type': 'LineString',
                    'coordinates': [
                        [120.28, 22.52],  # 河口
                        [120.38, 22.62],  # 高雄市内
                        [120.48, 22.72]   # 上游
                    ]
                }
            }
        ]
    }
    
    # 构建区域边界数据
    districts_data = {
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'properties': {'name': '台北区域', 'region': 'taipei'},
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [[
                        [121.35, 25.20],
                        [121.75, 25.20],
                        [121.75, 24.85],
                        [121.35, 24.85],
                        [121.35, 25.20]
                    ]]
                }
            },
            {
                'type': 'Feature',
                'properties': {'name': '台中区域', 'region': 'taichung'},
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [[
                        [120.35, 24.35],
                        [120.95, 24.35],
                        [120.95, 23.85],
                        [120.35, 23.85],
                        [120.35, 24.35]
                    ]]
                }
            },
            {
                'type': 'Feature',
                'properties': {'name': '台南区域', 'region': 'tainan'},
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': [[
                        [120.00, 23.25],
                        [120.50, 23.25],
                        [120.50, 22.45],
                        [120.00, 22.45],
                        [120.00, 23.25]
                    ]]
                }
            }
        ]
    }
    
    # 构建热图数据
    heatmap_data = {}
    for region in ['taipei', 'taichung', 'tainan']:
        region_airports = Airport.query.filter_by(region=region).all()
        region_data = []
        
        for airport in region_airports:
            # 计算热力点强度（基于设施总量）
            runway_count = Runway.query.filter_by(airport_id=airport.id).count()
            apron_count = ParkingApron.query.filter_by(airport_id=airport.id).count()
            oil_count = OilTank.query.filter_by(airport_id=airport.id).count()
            ammo_count = AmmunitionDepot.query.filter_by(airport_id=airport.id).count()
            
            intensity = 0.4  # 基础强度
            if runway_count > 0: intensity += 0.1
            if apron_count > 0: intensity += 0.1
            if oil_count > 0: intensity += 0.1
            if ammo_count > 0: intensity += 0.1
            
            # 强度值范围0.4-0.8
            region_data.append([airport.latitude, airport.longitude, intensity])
        
        heatmap_data[region] = {
            'data': region_data,
            'radius': 20
        }
    
    # 构建高程数据
    elevation_data = [
        {'latlng': [25.1, 121.8], 'elevation': 800},   # 山区
        {'latlng': [24.5, 121.5], 'elevation': 1200},  # 高山区
        {'latlng': [23.8, 121.3], 'elevation': 1500},  # 高山区
        {'latlng': [23.2, 121.0], 'elevation': 900},   # 山区
        {'latlng': [24.8, 120.8], 'elevation': 500},   # 丘陵区
        {'latlng': [24.0, 120.3], 'elevation': 200},   # 平原
        {'latlng': [23.0, 120.2], 'elevation': 100}    # 平原
    ]
    
    return jsonify({
        'airportLocations': airport_locations,
        'taiwanGeoData': taiwan_geo_data,
        'highwayData': highway_data,
        'riverData': river_data,
        'districtsData': districts_data,
        'heatMapData': heatmap_data,
        'elevationData': elevation_data
    })

@bp.route('/region-statistics', methods=['GET'])
def get_region_statistics():
    """获取区域设施统计"""
    region_stats = {}
    
    # 获取每个区域的设施数量
    for region in ['taipei', 'taichung', 'tainan']:
        # 计算该区域的机场数量
        airport_count = Airport.query.filter_by(region=region).count()
        
        # 获取该区域所有机场的ID
        airport_ids = [a.id for a in Airport.query.filter_by(region=region).all()]
        
        # 计算各类设施数量
        runway_count = Runway.query.filter(Runway.airport_id.in_(airport_ids)).count() if airport_ids else 0
        apron_count = ParkingApron.query.filter(ParkingApron.airport_id.in_(airport_ids)).count() if airport_ids else 0
        oil_count = OilTank.query.filter(OilTank.airport_id.in_(airport_ids)).count() if airport_ids else 0
        ammo_count = AmmunitionDepot.query.filter(AmmunitionDepot.airport_id.in_(airport_ids)).count() if airport_ids else 0
        
        # 统计各机场的容量
        hangar_capacity = db.session.query(func.sum(Airport.hangar_capacity)).filter(Airport.region == region).scalar() or 0
        shelter_capacity = db.session.query(func.sum(Airport.shelter_capacity)).filter(Airport.region == region).scalar() or 0
        mask_capacity = db.session.query(func.sum(Airport.mask_capacity)).filter(Airport.region == region).scalar() or 0
        cave_capacity = db.session.query(func.sum(Airport.cave_capacity)).filter(Airport.region == region).scalar() or 0
        
        region_stats[region] = {
            'airports': airport_count,
            'runways': runway_count,
            'parkingAprons': apron_count,
            'oilTanks': oil_count,
            'ammunitionDepots': ammo_count,
            'hangarCapacity': float(hangar_capacity),
            'shelterCapacity': float(shelter_capacity),
            'maskCapacity': float(mask_capacity),
            'caveCapacity': float(cave_capacity),
            'totalCapacity': float(hangar_capacity + shelter_capacity + mask_capacity + cave_capacity)
        }
    
    return jsonify(region_stats)

@bp.route('/airports-by-capability', methods=['GET'])
def get_airports_by_capability():
    """根据能力类型获取机场列表"""
    capability = request.args.get('capability', 'all')
    region = request.args.get('region', 'all')
    
    # 构建基础查询
    query = Airport.query
    
    # 按区域过滤
    if region and region != 'all':
        query = query.filter(Airport.region == region)
    
    # 按能力类型过滤
    if capability and capability != 'all':
        if capability == 'runways':
            query = query.join(Runway, Runway.airport_id == Airport.id).distinct()
        elif capability == 'parking-aprons':
            query = query.join(ParkingApron, ParkingApron.airport_id == Airport.id).distinct()
        elif capability == 'oil-tanks':
            query = query.join(OilTank, OilTank.airport_id == Airport.id).distinct()
        elif capability == 'ammunition-depots':
            query = query.join(AmmunitionDepot, AmmunitionDepot.airport_id == Airport.id).distinct()
    
    airports = query.all()
    
    # 格式化结果
    result = []
    for airport in airports:
        # 获取该机场的设施数量
        runway_count = Runway.query.filter_by(airport_id=airport.id).count()
        apron_count = ParkingApron.query.filter_by(airport_id=airport.id).count()
        oil_count = OilTank.query.filter_by(airport_id=airport.id).count()
        ammo_count = AmmunitionDepot.query.filter_by(airport_id=airport.id).count()
        
        # 计算能力值
        capability_value = 0
        if capability == 'runways':
            capability_value = runway_count * 10
        elif capability == 'parking-aprons':
            capability_value = apron_count * 8
        elif capability == 'oil-tanks':
            capability_value = oil_count * 6
        elif capability == 'ammunition-depots':
            capability_value = ammo_count * 7
        else:
            capability_value = (runway_count * 10 + apron_count * 8 + oil_count * 6 + ammo_count * 7) / 4
        
        result.append({
            'id': airport.id,
            'name': airport.name,
            'region': airport.region,
            'latitude': airport.latitude,
            'longitude': airport.longitude,
            'facilitiesCount': runway_count + apron_count + oil_count + ammo_count,
            'capabilityValue': capability_value,
            'runways': runway_count > 0,
            'parkingAprons': apron_count > 0,
            'oilTanks': oil_count > 0,
            'ammunitionDepots': ammo_count > 0
        })
    
    # 按设施数量排序
    result.sort(key=lambda x: x['facilitiesCount'], reverse=True)
    
    return jsonify(result) 